package com.zhz.controller;

import com.zhz.pojo.Order;
import com.zhz.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import java.util.UUID;

@Controller
@Slf4j
public class IndexController {

    @Resource
    private OrderService service;

    /**
     * 首页
     *
     * @return
     */
    @RequestMapping("/index")
    public String index() {
        return "index";
    }

    @RequestMapping("/main")
    public String main(String action, String amount,
                       String phone, String subject, Model model) {
        log.info("action={}",action);
        String no = null;
        if (action != null && action.length() > 0) {
            switch (action) {
                case "add":
                    //商户订单号
                    String orderNo = UUID.randomUUID().toString().replaceAll("-", "");
                    String body = "充值号码：" + phone + "，充值金额：" + amount + "元";

                    Order order = new Order();
                    order.setAmount(Double.parseDouble(amount));
                    order.setBody(body);
                    order.setOrderNo(orderNo);
                    order.setPhone(phone);
                    order.setStatus(0);  // 0-待支付   1-已支付
                    order.setSubject(subject);

                    int result = service.save(order);
                    if (result != 1) {
                        //下单失败，跳转至错误页面
                        model.addAttribute("error", "下单失败");
                        return "error";
                    }
                    no = orderNo;
                    //下单成功，继续执行
                case "topay":
                    Order o = service.findOrderNO(no);
                    model.addAttribute("order", o);
                    return "pay";
                default:
                    model.addAttribute("error", "404");
                    return "error";
            }
        } else {
            model.addAttribute("error", "404");
            return "error";
        }
    }
}
